package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //
        password = DigestUtils.md5DigestAsHex(password.getBytes());//加密后与数据库比对

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    public void add_(EmployeeDTO emp){
        Employee emp_ = new Employee();
        //属性拷贝
        BeanUtils.copyProperties(emp,emp_);
        //设置默认密码
        emp_.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置时间
        emp_.setUpdateTime(LocalDateTime.now());
        emp_.setCreateTime(LocalDateTime.now());
        //设置默认状态
        emp_.setStatus(StatusConstant.ENABLE);
        //
        emp_.setCreateUser(BaseContext.getCurrentId());
        emp_.setUpdateUser(BaseContext.getCurrentId());
        //
        employeeMapper.addemp(emp_);

    }


    public PageResult pagesearch(EmployeePageQueryDTO dto){
//        //Integer index = (dto.getPage()-1)*dto.getPageSize();
//        if(dto.getPage()==0 || dto.getPageSize()==0){
//            dto.setPage(1);
//            dto.setPageSize(10);
//        }//设置默认值
//        dto.setPage((dto.getPage()-1)*dto.getPageSize());//把page改为起始索引
//        List<Employee> result = employeeMapper.search_by_page(dto);//查询员工列表
//        Long records = employeeMapper.records();//记录数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<Employee> result = employeeMapper.search_by_page(dto);
        Long records = result.getTotal();
        PageResult pageresult = new PageResult(records,result.getResult());
        return pageresult;
    }

    public void set_emp(Integer status, Integer id){
        employeeMapper.update_status(status,id);
    }

    public void edit(EmployeeDTO dto){
        employeeMapper.editemp(dto);
    }

    public Employee searchbyID(Integer id){
        return employeeMapper.search(id);
    }
    @Transactional
    public void edit_password(@RequestBody PasswordEditDTO dto){
        String passwordByid = employeeMapper.getPasswordByid(dto.getEmpId());
        String oldpassword = DigestUtils.md5DigestAsHex(dto.getOldPassword().getBytes());
        if(passwordByid == null || !passwordByid.equals(oldpassword)){
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        else{
            dto.setNewPassword(DigestUtils.md5DigestAsHex(dto.getNewPassword().getBytes()));//将新密码转成md5加密后再存入数据库
            employeeMapper.editPassword(dto);
        }
    }
}
